#ifndef TEMPLE_UTIL_PROPER_H_
#define TEMPLE_UTIL_PROPER_H_

#include "util/stdc.h"
#include "util/string.h"
#include <map>
namespace util {

class Proper
{
public:
    int load(const string &path)
    {
        FILE *pf = NULL;
        char buf[8192];

        pf = fopen(path.c_str(), "rb");
        if (!pf)
            return 1;

        while(fgets(buf, sizeof(buf), pf))
        {
            char *pos = buf;
            int len;

            len = pass_ws(pos);
            pos += len;

            if (pos[0] == 0)   //empty line
                continue;

            if (pos[0] == '#' || pos[0] == ';') //comment line
                continue;

            len = get_key(pos);

            if (pos[len] != '=')
                continue;

            string key;
            string val;

            key.assign(pos, len);
            key = trim(key);

            pos += len+1;

            len = get_value(pos);
            val.assign(pos, len);
            val = trim(val);

            map[key] = val;
        }

        fclose(pf);
        return 0;
    }

    inline const string &get(const string &key, const string &def = "") const
    {
        std::map<string, string>::const_iterator iter = map.find(key);

        if (iter != map.end())
            return iter->second;

        return def;
    }

    inline int get(const string &key, int def = 0) const
    {
        std::map<string, string>::const_iterator iter = map.find(key);

        if (iter != map.end())
            return atoi(iter->second.c_str());

        return def;
    }

    inline std::vector<string> &mget(const string &key, char sep=',') const
    {
        std::map<string, string>::const_iterator iter = map.find(key);

        if (iter != map.end())
            return split(iter->second);

        return std::vector<string>();
    }

private:
    std::map<string, string> map;

    inline int pass_ws(char *buf)
    {
        int sum = 0;

        while (*buf != 0 && isspace(*buf))
        {
            ++sum;
            ++buf;
        }

        return sum;
    }

    int get_key(char *buf)
    {
        int sum = 0;

        while (*buf != 0 && *buf != '=')
        {
            ++sum;
            ++buf;
        }

        return sum;
    }

    int get_value(char *buf)
    {
        int sum = 0;

        while (*buf != 0 && *buf != '\r' && *buf != '\n')
        {
            ++sum;
            ++buf;
        }

        return sum;
    }
};

}
#endif //TEMPLE_UTIL_PROPER_H_
